<?php
/*
 * This class holds all function that communicate with the database.
 * 
 * To create a new connection, just call this class with $var = new Database();
 * Then call the function needed with $var->the_function_you_need;
 * 
 * function get($table,$fields){}
 * It is recommended that you only sellect the fields needed from the table.
 * When selecting use an array like so: $var->get('table',array('col0','col1','col2')); 
 * 
 * 
 * 
 */

class Database {

	private $db = array();
	private $connection;

	function __construct(){
		$this->db['host'] 		= 'localhost';
		$this->db['user'] 		= '2bet_db';
		$this->db['password'] 	= 'woH2UirEfdjYiEK';
		$this->db['db'] 		= '2bet_db';
		
		$this->connect();
	}
	
	function connect(){
		$db = $this->db;
		$mysqli = new mysqli($db['host'], $db['user'], $db['password'], $db['db']);
		
		if ($mysqli->connect_error) {
    		die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
		}
		
		$this->connection = $mysqli;
	}
	public function get($atts){
		extract($atts);
					
		extract($defaults = array(
		'table'	=> null,
		'fields'=> array(),
		'where'	=> array(),
		'group' => false,
		'order'	=> false,
		'limit' => false,
		'log'	=> false,
		'return_type' => 'object'
		),EXTR_SKIP);

		if(!empty($table)){
		
			$select = (!empty($fields)) ? implode(',',$fields) : '*';
			
			$query = "Select ".$select." from ".$table;
			if(count($where) > 0){
				$i = 0;
				foreach($where as $attribute => $value){
					if($i > 0){
						$query .= ' && where '.$attribute.'='.$value;
					} else {
						$query .= ' where '.$attribute.'='.$value;
					}
				$i++;
				}
			} 
			if($group) $query .= ' group by '.$group;
			if($order) $query .= ' order by '.$order;
			if($limit) $query .= ' limit '.$limit;
			
			$result = $this->connection->query($query);
			
			if($log){
				$log = $this->connection->query("DESCRIBE ".$query);
				$this->log_sql($log,base64_encode($query));
			}
			
			if ($result) {
				if($return_type == 'row'){
					$row = $result->fetch_object();
					$return = $row->user_id;
				} else {
					$return = $result;
				}
			}
		} else {
			
			$result = $this->connection->error;
			
		}
		
		return $return;
	}
	public function get_bid_status(){
		$result = $this->connection->query('Select b.product_id,b.user_id,b.sum,b.timestamp,u.username
											from bid_sum b
											left join users u on b.user_id = u.user_id
											order by b.timestamp desc');
		return $result;
	}
	public function get_query($query){
		$result = $this->connection->query($query);
		return $result;
	}
	public function insert($table,$array){
		
		$keys = array_keys($array);
		$values = array_values($array);
		
		$t = $this->connection->query('Insert into '.$table.' ('.implode(',',$keys).') values ('.implode(',',$values).')');

		if($t){
			return true;
		} else {
			echo $this->connection->error;
			return false;
		}
	}
	public function check_wallet($user_id){
		$wallet = $this->connection->query('Select deposit from users_wallet where user_id = '.$user_id);
		$row = $wallet->fetch_object();
		return $row->deposit;
	}
	public function update($product_id,$user_id){
		$test = $this->connection->query('Select bid_id,user_id from bid_sum where product_id = "'.$product_id.'"');
		
		$amount = $this->check_wallet($user_id);
		if($amount > 0){
			if($test->num_rows > 0){
				$row = $test->fetch_object();
				if($row->user_id != $user_id){
					$this->connection->query('Update bid_sum set user_id = "'.$user_id.'",sum = sum+1,timestamp = "'.time().'" where product_id = "'.$product_id.'"');
					$this->connection->query('update users_wallet set deposit = deposit-1 where user_id = "'.$user_id.'"');
					$amount = $amount-1;
				}
			} else {
				$this->connection->query('Insert into bid_sum (product_id,user_id,sum,timestamp) values ("'.$product_id.'","'.$user_id.'",1,'.time().')');
				$this->connection->query('update users_wallet set deposit = deposit-1 where user_id = "'.$user_id.'"');
				$amount = $amount-1;
			}
			
			$this->insert('bid_history', array('product_id'=>$product_id,'user_id'=>$user_id,'value'=>1,'timestamp'=>time()));
			return json_encode(array('user_id'=>$user_id,'amount'=>$amount));
			}
	}
	public function update_wallet($user_id,$amount){
		$user = $this->connection->query('Select user_id from users where userid = "'.$user_id.'"');
		$user_row = $user->fetch_object();
					
		$deposit = $this->connection->query('Select deposit from users_wallet where user_id="'.$user_row->user_id.'"');
		$row = $deposit->fetch_object();
		$newdeposit = $row->deposit + $amount;
		$this->connection->query('update users_wallet set deposit = "'.$newdeposit.'" where user_id = "'.$user_row->user_id.'"');
	}
	public function new_wallet($userid, $username, $time){
		$result1 = $this->connection->query('Insert into users (userid,username) values ("'.$userid.'","'.$username.'")');
		if($result1) {
			$userid = $this->connection->query('SELECT user_id from users WHERE username="'.$username.'"');
			$row = $userid->fetch_object();
			$userid = $row->user_id;
			$result2 = $this->connection->query('Insert into users_wallet (user_id, last_deposit) values ("'.$userid.'", "'.$time.'")');
		}
		if($result2){
			return true;
		} else {
			echo $this->connection->error;
			return false;
		}
	}
	public function delete($table,$array){
		
		$field 	= array_keys($array);
		$id 	= array_values($array);
		
		if($this->connection->query('Delete from '.$table.' where "'.$field[0].'" = "'.$id[0].'")')){
			return true;
		} else {
			return false;
		}
		
	}
	public function free_result($result){
		echo 'Freeing result ...';
		$result->free();
	}
	public function close_connection($con){
		echo 'Closing connection ...';
		$con->close();
	}

	public function log_sql($query,$statement) {
		$explain = serialize($row = $query->fetch_assoc());
		
		$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/application/logs/queries.txt','a');
		fwrite($fp, time().'#'.base64_decode($statement).'#'.$explain."\n");
		fclose($fp);
	}

}